package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CusterException;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Address;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 黑马程序员
 * @since 2022-06-06
 */
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrderDetailService ordersDetialService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrdersService ordersService;

    @Transactional
    public void saveByOrders(Orders orders) {

        log.info("{}", orders);
        Long userId = BaseContext.getCurrentId();
        //获取当前用户购物车数据
        LambdaQueryWrapper<ShoppingCart> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingList = shoppingCartService.list(qw1);
        //获取订单号
        long id = IdWorker.getId();
        //加减乘除不会有线程安全问题
        AtomicInteger amount = new AtomicInteger(0);
        if (shoppingList == null || shoppingList.size() == 0) {
            throw new CusterException("用户信息有误，不能下单");
        }
        //把购物车的数据复制到订单明细中
        List<OrderDetail> shoppingCollect = shoppingList.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail);
            orderDetail.setOrderId(id);
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        //查询user对象
        User user = userService.getById(userId);
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        LambdaQueryWrapper<AddressBook> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(AddressBook::getId, addressBookId);
        List<AddressBook> addressBooklist = addressBookService.list(qw2);
        //判断是否有值
        if (addressBooklist == null || addressBooklist.size() == 0) {
            throw new CusterException("用户地址信息有误，不能下单");
        }
//        List<Orders> ordersList = addressBooklist.stream().map(item -> {
//            BeanUtils.copyProperties(item, orders);
//            BeanUtils.copyProperties(user, orders);
//            //总金额
//            orders.setId(id);
//            orders.setAmount(new BigDecimal(amount.get()));
//            orders.setNumber(String.valueOf(id));
//            orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
//                    + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
//                    + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
//                    + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
//            orders.setOrderTime(LocalDateTime.now());
//            orders.setCheckoutTime(LocalDateTime.now());
//            orders.setStatus(i);
//            return orders;
//        }).collect(Collectors.toList());
        orders.setId(id);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(id));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        ordersDetialService.saveBatch(shoppingCollect);
        ordersService.save(orders);

        //清空购物车
        shoppingCartService.remove(qw1);
    }


    @Transactional
    public Page<OrdersDto> selectByPage(int page, int pageSize) {
        Page<OrdersDto> pgaeInfo3 = new Page<>();
        List<OrdersDto> page3 = new ArrayList<>();
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<Orders> qw4 = new LambdaQueryWrapper<>();
        qw4.eq(Orders::getUserId, userId);
        qw4.orderByDesc(Orders::getOrderTime);
        List<Orders> collect = ordersService.list(qw4);
        //获得用户下所有的地址Id
        List<Long> collect1 = collect.stream().map(item -> {
            return item.getId();

        }).collect(Collectors.toList());

        for (Long aLong : collect1) {
            OrdersDto ordersDto = new OrdersDto();
            LambdaQueryWrapper<Orders> qw2 = new LambdaQueryWrapper<>();
            qw2.eq(Orders::getId, aLong);
            qw2.orderByDesc(Orders::getOrderTime);
            qw2.eq(Orders::getUserId, userId);
            Orders one1 = ordersService.getOne(qw2);
            BeanUtils.copyProperties(one1, ordersDto);
            LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
            qw.eq(OrderDetail::getOrderId, aLong);
            List<OrderDetail> list = ordersDetialService.list(qw);
            ordersDto.setOrderDetails(list);
            page3.add(ordersDto);
            pgaeInfo3.setRecords(page3);
        }

        return pgaeInfo3;

    }

    @Transactional
    public void again(Orders orders) {
        LambdaQueryWrapper<OrderDetail> qw =new LambdaQueryWrapper<>();
        qw.eq(OrderDetail::getOrderId,orders.getId());
        List<OrderDetail> list = ordersDetialService.list(qw);
        List<ShoppingCart> shoppingList =new ArrayList<>();
        for (OrderDetail orderDetail : list) {
            ShoppingCart shoppingCart =new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingList.add(shoppingCart);
        }
        shoppingCartService.saveBatch(shoppingList);
    }
}
